﻿#include <qg/qg.h>

using namespace tpl;

Point CalcRotPoint(int x, int y, float fs, float fc, const Point& vp)
{
	float u = fc * x - fs * y;
	float v = fs * x + fc * y;
	return Point((int)u + vp.width, (int)v + vp.height);
}

void rectdraw(qgDevice* dev, qgTexture* tex, const Rect& bound, float rot = 0.0f)
{
	Point hf(bound.Width() / 2, bound.Height() / 2);
	Point vp(bound.left + hf.x, bound.top + hf.y);
	Rect rt(-hf.x, -hf.y, hf.x, hf.y);

	float fs, fc;
	k_sincos(rot, &fs, &fc);

	Point pts[4] =
	{
		CalcRotPoint(rt.left, rt.top, fs, fc, vp),
		CalcRotPoint(rt.right, rt.top, fs, fc, vp),
		CalcRotPoint(rt.left, rt.bottom, fs, fc, vp),
		CalcRotPoint(rt.right, rt.bottom, fs, fc, vp),
	};

	ColorValue ccs[4] =
	{
		ColorValue(0xFFFF0000),
		ColorValue(0xFF00FF00),
		ColorValue(0xFF0000FF),
		ColorValue(0xFFFFFFFF),
	};

	Vec2 crds[4] =
	{
		Vec2(0.0f, 0.0f),
		Vec2(1.0f, 0.0f),
		Vec2(0.0f, 1.0f),
		Vec2(1.0f, 1.0f),
	};

	dev->DrawPolyStrip(4, pts, NULL, tex, crds);
}

int main(void)
{
	k_mesg("OFF TEXTURE TEST\n");

	qgDevice* dev = qgDevice::New("dx9", 640, 480, QGSDF_LAYOUT | QGSDF_AUTO /*| QGSDF_INFO*/);

	if (dev)
	{
		dev->Mount(QG_WORK_PATH);

		qgStub* stub = dev->GetStub();
		qgFreeType* font = qgFreeType::New();

		//qgTexture* tex = dev->CreateTexture("/texture/z.png", 0);
		qgTexture* tex = dev->CreateTexture("wof2.png", 0);

		float f = 0.0f;

		//
		while (dev->Run())
		{
			float adv = stub->GetAdvance();

			f += KM_PI_HOH * adv;
			f = k_cprad(f);

			//
			dev->Enter();

			Rect rt(Point(20, 20), Point(tex->GetWidth() / 2, tex->GetHeight() / 2));
			rectdraw(dev, tex, rt.Offset(100, 100), f);
			dev->DrawRect(rt, tpl::ColorValues::White, tex);

			font->WriteFormat(5, 5, 0, "[%.2f]", stub->GetRunFps());

			dev->Leave();
			dev->Flush();
		}

		font->Unload();
		dev->Unload();
	}

	return 0;
}
